package com.yjy.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.system.comm.util.BaseUtils;
import com.system.common.pojo.SysMenu;
import com.system.common.pojo.SysRole;
import com.system.common.pojo.SysUser;
import com.yjy.service.SysMenuService;
import com.yjy.service.SysRoleService;
import com.yjy.service.SysUserService;

@Controller
@RequestMapping("deng")
public class LoginController {
	
	@Autowired
	private SysMenuService menuService;
	
	@Autowired
	private SysRoleService roleService;
	
	@Autowired
	private SysUserService userService;
	
	@RequestMapping("insert")
	public String login(){
		return "login";
	}
	
	@RequestMapping("login")
	public String login(String account,String password,Model model,HttpSession session){
		String pass=BaseUtils.encrypt(password, BaseUtils.PASSWORD_KEY);
		SysUser user=userService.getByAP(account, pass);
		List<SysMenu> menus=new ArrayList<>();
		if (user==null) {
			return "login";
		}else{
			if (user.getAccount().equals("super")) {
				menus=menuService.selectMenu();
			}else {
				List<SysRole> roles=roleService.selectRole(user.getUserId());
				for (SysRole sysRole : roles) {
					List<SysMenu>   list=menuService.selectMenu(sysRole.getRoleId());
					for (SysMenu sysMenu : list) {
						menus.add(sysMenu);
					}
				}
			}
			model.addAttribute("menuList", menus);
			session.setAttribute("user", user);
			model.addAttribute("user", user);
			return  "index";
		}
	}
	
	@RequestMapping("exit")
	public String exit(HttpSession session){
		session.invalidate();
		return "login";
	}
	
	@RequestMapping("change")
	public String change(String pass,HttpSession session){
		SysUser user=(SysUser) session.getAttribute("user");
		pass=BaseUtils.encrypt(pass, BaseUtils.PASSWORD_KEY);
		Map<String, Object> map=new HashMap<>();
		if (pass!=null) {
			map.put("pass", pass);
			map.put("userId", user.getUserId());
		}
		if (userService.change(map)) {
			return "login";
		}
		return "";
	}
	
}
